package com.elitel.conf;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Slf4j
@Configuration
@AutoConfigureAfter(MybatisAutoConfiguration.class)
class MybatisInterceptorConfig {

    @Bean
    public AuditInterceptor auditInterceptor() {
        AuditInterceptor interceptor = new AuditInterceptor();

        // 1. 通过属性配置
        Properties properties = new Properties();
        properties.setProperty("enableCreateTime", "true");
        properties.setProperty("enableUpdateTime", "true");
        properties.setProperty("enableAuditUser", "true");
        interceptor.setProperties(properties);
        return interceptor;
    }


    /**
     * 将拦截器注册到所有 SqlSessionFactory
     */
    @Bean
    public String registerInterceptor(SqlSessionFactory[] sqlSessionFactories,
                                      AuditInterceptor auditInterceptor) {
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactories) {
            org.apache.ibatis.session.Configuration configuration =
                    sqlSessionFactory.getConfiguration();

            if (!containsInterceptor(configuration, AuditInterceptor.class)) {
                configuration.addInterceptor(auditInterceptor);
                log.info("注册MyBatis拦截器到SqlSessionFactory: {}", sqlSessionFactory);
            }
        }
        return "interceptor-registered";
    }

    private boolean containsInterceptor(org.apache.ibatis.session.Configuration configuration,
                                        Class<?> interceptorClass) {
        try {
            for (Interceptor interceptor : configuration.getInterceptors()) {
                if (interceptor.getClass().equals(interceptorClass)) {
                    return true;
                }
            }
        } catch (Exception e) {
            // 处理旧版本兼容性问题
        }
        return false;
    }
}